<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="物品名称" prop="productName">
        <el-input
            v-model="queryParams.productName"
            placeholder="请输入物品名称"
            clearable
            style="width: 260px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.useStatus" placeholder="用户状态" clearable style="width: 240px">
          <el-option v-for="dict in product_type" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:dict:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:dict:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="info"-->
<!--            plain icon="Upload"-->
<!--            @click="handleImport">-->
<!--          导入-->
<!--        </el-button>-->
<!--      </el-col>-->

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="物品名称" align="center" prop="productName"/>
      <el-table-column label="物品简称" align="center" prop="shortName"/>
      <el-table-column label="收费" align="center" prop="chargeItemName"/>
      <el-table-column label="物品分类" align="center" prop="productCategoryName"/>
      <el-table-column label="供应商" align="center" prop="supplierName"/>
      <el-table-column label="规格" align="center" prop="specification"/>
      <el-table-column label="单位" align="center" prop="unit"/>
      <!-- 状态列（开关） -->
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-switch
              v-model="row.useStatus"
              :active-value="'1'"
              :inactive-value="'2'"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="最后修改人" align="center" prop="updateBy"  width="180" />
      <el-table-column label="最后修改时间" align="center" prop="updateTime" width="180"/>
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="dictRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="物品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入物品名称" />
        </el-form-item>
        <el-form-item label="物品简介" prop="shortName">
          <el-input v-model="form.shortName" placeholder="请输入物品简介" />
        </el-form-item>

        <el-form-item label="物品分类" prop="productCategoryId">
          <el-select v-model="form.productCategoryId"
                     @change="(val) => console.log('选中的值:', val, '类型:', typeof val)"
                     placeholder="物品分类" clearable>
            <el-option v-for="dict in categoryList" :key="dict.id" :label="dict.categoryName"
                       :value="dict.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="收费项目" prop="chargeItemId">
          <el-input v-model="form.chargeItemId" placeholder="请输入收费项目" />
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="form.supplierId" placeholder="供应商" clearable>
            <el-option v-for="dict in supplierList" :key="dict.id" :label="dict.supplierName"
                       :value="dict.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="状态" prop="useStatus">
          <el-select v-model="form.useStatus" placeholder="用户状态" clearable>
            <el-option v-for="dict in product_type" :key="dict.value" :label="dict.label"
                       :value="dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea"  v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Dict">
import { toRaw } from 'vue'
import useDictStore from '@/store/modules/dict'
import { listType,updateStatus,getListAllCategory,getListAllSupplier,addType,getType,delType,updateType } from "@/api/system/goodsManage/goods"
import { ElMessageBox, ElMessage } from 'element-plus'

const { proxy } = getCurrentInstance()
const {sys_normal_disable, product_type} = proxy.useDict("sys_normal_disable", "product_type")
const typeList = ref([])
const categoryList = ref([])
const supplierList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dateRange = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productName: undefined,
    shortName: undefined,
    // productCategoryId: '',
    // chargeItemId: '',
    // supplierId: '',
    specification: undefined,
    unit: undefined,
    remark: undefined,
    //useStatus: ''
  },
  rules: {
    productName: [{ required: true, message: "物品名称不能为空", trigger: "blur" }],
    productCategoryId : [{ required: true, message: "物品分类不能为空", trigger: "change" }],
    specification : [{ required: true, message: "规格不能为空", trigger: "blur" }],
    unit : [{ required: true, message: "单位不能为空", trigger: "blur" }],
    useStatus : [{ required: true, message: "状态不能为空", trigger: "change" }]
  },
})

const { queryParams, form, rules } = toRefs(data)

// 开关变化时的处理函数
const handleStatusChange = (row) => {
  console.log('状态改变:', row)
  const action = row.useStatus === '1' ? '启用' : '停用'
  const message = `确定要${action}【${row.productName}】吗？`
  ElMessageBox.confirm(message, '操作确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
        const params = {
          id: row.id,
          useStatus: row.useStatus
        }
        updateStatus(params)
            .then(() => {
              ElMessage.success(`${action}成功！`)
            })
            .catch((err) => {
              ElMessage.error(`操作失败：'请稍后重试'}`)
              row.useStatus = row.useStatus === '1' ? '2' : '1'
            })
      })
      .catch(() => {
        row.useStatus = row.useStatus === '1' ? '2' : '1'
      })
}

/** 查询列表 */
function getList() {
  loading.value = true
  listType(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    typeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
/** 查询所有物品分类 */
function ListAllCategory(){
  getListAllCategory(proxy.addDateRange(queryParams.value)).then(response => {
    console.log(response)
    categoryList.value = response.rows
  })
}
/** 查询所有供应商 */
function ListAllSupplier(){
  getListAllSupplier(proxy.addDateRange(queryParams.value)).then(response => {
    console.log(response)
    supplierList.value = response.rows
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    dictId: undefined,
    productName: undefined,
    shortName: undefined,
    productCategoryId: '',
    chargeItemId: '',
    supplierId: '',
    specification: undefined,
    unit: undefined,
    remark: undefined,
    useStatus: ''
  }
  proxy.resetForm("dictRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加仓库"
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  console.log(ids.value)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const dictId = row.id
  getType(dictId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改仓库"
  })
}


/** 提交按钮 */
function submitForm() {
  console.log('最终提交:', { ...data.queryParams })
  //return false
  proxy.$refs["dictRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        updateType(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        console.log(form.value)
        // const submitData = toRaw(data.queryParams)
        // console.log('实际提交的数据:', submitData) // 再确认一次
        // return false;
        addType(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  console.log(row)
  const dictIds = row.id || ids.value
  proxy.$modal.confirm('是否确认删除编号为"' + dictIds + '"的数据项？').then(function() {
    return delType(dictIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}



getList()
ListAllCategory()
ListAllSupplier()
</script>
